/**
 * http基础类
 */
import axios from 'axios'
import hooks from './hook'
let config = require(`@/config/${process.env.ENV_CONFIG||'pro'}.config.json`);

export default {

    async send(options) {
        options = {
            toastError: true,
            ...options
        }
        console.log('request', options)
        options.loadingText && hooks.callHook('showLoading', options.loadingText)
        options.headers = {
            'content-type': options.contentType,
            ...options.headers
        }

        options.url = (options.url.indexOf('http://') === 0 || options.url.indexOf('https://') === 0) ? options.url : (config[options.domainKey || 'baseUrl'] + options.url);
        if (options.method === 'get') {
            options.params = options.data;
        } else {
            if (options.contentType === 'application/x-www-form-urlencoded') {
                let form = new FormData();
                let keys = Object.keys(options.data);
                keys.forEach(key => {
                    form.append(key, options.data[key]);
                });
                options.data = form;
            }
        }
        await hooks.callHook('beforeHttp', options)
        return axios(options).then(res => {
            console.log('request finish', res.data)
            options.loadingText && hooks.callHook('hideLoading')
            return hooks.callHook('resolveHttpSuccess', res, options)
        }).catch(err => {
            console.error('request error', err)
            options.toastError && hooks.callHook('toastError', err.msg || err.toString())
            return hooks.callHook('catchHttpError', err, options)
        })
    },

    get(options) {
        options.method = 'get';
        return this.send(options);
    },

    postJson(options) {
        options.contentType = 'application/json';
        return this.post(options);
    },

    postForm(options) {
        options.contentType = 'application/x-www-form-urlencoded';
        return this.post(options);
    },

    post(options) {
        options.method = 'post';
        return this.send(options);
    },

    put(options) {
        options.method = 'put';
        return this.send(options);
    },

    delete(options) {
        options.method = 'delete';
        return this.send(options);
    }

}
